import { Component, OnInit, ViewChild, Type } from '@angular/core';
import { STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFRadioWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { EAEnvironmentService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { SystemService } from '../../services/system.service';

@Component({
  selector: 'app-sys-setting-components-insurance-set',
  templateUrl: './insurance-set.component.html',
  styleUrls: ['./insurance-set.component.less']
})
export class InsuranceSetComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  schema: SFSchema = {};
  addSchema: SFSchema = {};
  _$expand = false;
  editText = '';
  formData :any;
  isVisible = false;
  edit = false;
  editId = false;

  columns: STColumn[] = [
    { title: '公告标题', index: 'announcementTitle' },
    { title: '创建时间', index: 'createTime' },
    { title: '发送时间', index: 'sendTime' },
    { title: '公告内容', index: 'announcementContent' },
    {
      title: '操作',
      className: 'text-center',
      buttons: [
        {
          text: '编辑',
          click: item => this.roleAction(item, 2)
        },
        {
          text: '删除',
          click: item => this.deleteAction(item)
        },
      ]
    }
  ];

  selectedRows: any[] = [];

  get reqParams (){ 
    return {
    ...this.sf?.value,
  }};

  constructor(
    public service: SystemService, 
    private nzModalService: NzModalService,
    public shipperservice: ShipperBaseService,
    private envSrv: EAEnvironmentService,
    ) {}

  ngOnInit(): void {
    this.initSF()
    this.initSFFre()
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }
    /**
  * 伸缩查询条件
  */
     expandToggle(): void {
      this._$expand = !this._$expand;
      this.sf?.setValue('/_$expand', this._$expand);
    }
    /**
   * 查询字段个数
   */
     get queryFieldCount(): number {
      return Object.keys(this.schema?.properties || {}).length;
    }
  initSF(){
  this.schema = {
    properties: {
      _$expand: { type: 'boolean', ui: { hidden: true } },
      announcementTitle: {
        type: 'string',
        title: '按钮名称',
        ui: { placeholder: '请输入' }
      },
      createTime: {
        title: '创建时间',
        type: 'string',
        ui: {
          widget: 'date',
          mode: 'range',
          format: 'yyyy-MM-dd',
          allowClear: true,
        } as SFDateWidgetSchema
      },
    }
    
  };
  this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  initSFFre() {
  this.addSchema = {
    properties: {
      appIdList: {
        type: 'string',
        title: '发布平台',
        enum: [
          { label: '运营后台', value: this.envSrv.env.appId },
          // { label: '货主后台', value: this.envSrv.env.HzappId },
          // { label: '司机端', value: this.envSrv.env.sjappId }
        ],
        ui: {
          widget: 'select',
          mode: 'multiple',
          errors: { required: '请选择' },
          placeholder: '请选择'
        }
      },
      announcementTitle: {
        type: 'string',
        title: '公告标题',
        ui: { placeholder: '请输入' }
      },
      announcementContent: {
        type: 'string',
        title: '公告内容',
        ui: { placeholder: '请输入' }
      },
      sendTime: {
        title: '发送时间',
        type: 'string',
        format: 'date-time',
        ui: {
          allowClear: true,
        }
      },
  },
  required: ['name', 'i18n', 'text']
  };
this.ui2 = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
}
  roleAction(value: any,item?: any) {
    if(item === 1) {
      this.edit = false;
      this.editText = '新增';
      this.formData = {};
    } else {
      this.service.request(this.service.$api_getAnnouncementInfoById_detail, {id: value.id}).subscribe((res: any) => {
        console.log(res)
        if(res) {
          this.formData = res;
        }
      })
      this.edit = true;
      this.editId = value.id;
      this.editText = '编辑';
    }
   this.isVisible = true;
  }

  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_delete_deleteAnnouncementInfoById, [item.id]).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('删除成功！');
            this.st.reload(1)
          }
        })
      }
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }
  handleCancel() {
    this.isVisible = false
  }

  handleOK() {
    console.log(this.sfFre.value)
    if(!this.sfFre.valid) {
      this.service.msgSrv.warning('请正确填写完整！')
      return
    }
    var c = new Date(this.sfFre.value.sendTime);
    this.sfFre.value.sendTime =
      c.getFullYear() +
      '-' +
      this.addPreZero(c.getMonth() + 1) +
      '-' +
      this.addPreZero(c.getDate()) +
      ' ' +
      this.addPreZero(c.getHours()) +
      ':' +
      this.addPreZero(c.getMinutes()) +
      ':' +
      this.addPreZero(c.getSeconds());
    const params ={
      ...this.sfFre.value
    }
    if(this.editId) {
      params.id = this.editId
      console.log(params)
      this.service.request(this.service.$api_modifyAnnouncementInfo, params).subscribe((res:any) => {
        if(res) {
         this.service.msgSrv.success('保存成功！')
         this.isVisible = false
         this.st.reload();
        }
      })
    } else {
      this.service.request(this.service.$api_addAnnouncementInfo, params).subscribe((res:any) => {
        if(res) {
         this.service.msgSrv.success('保存成功！')
         this.isVisible = false
         this.st.reload();
        }
        }
      )}
}
  addPreZero(num: any) {
    if (num < 10) {
      return '0' + num;
    } else {
      return num;
    }
  }
}
